
import { defineStore } from 'pinia'
import type { Contact } from '@/types'
import { ref, computed } from 'vue'

export const useContactStore = defineStore('contact', () => {
  const contacts = ref<Contact[]>([
    {
      id: '1',
      username: 'zhangsan',
      nickname: '张三',
      avatar: '/images/avatars/avatar1.jpg',
      signature: '生活就像一盒巧克力',
      region: '北京',
      isStarred: true,
      initial: 'Z'
    },
    {
      id: '2',
      username: 'lisi',
      nickname: '李四',
      avatar: '/images/avatars/avatar2.jpg',
      signature: '今天天气真好',
      region: '上海',
      isStarred: false,
      initial: 'L'
    },
    {
      id: '3',
      username: 'wangwu',
      nickname: '王五',
      avatar: '/images/avatars/avatar3.jpg',
      signature: '努力成为更好的自己',
      region: '广州',
      isStarred: true,
      initial: 'W'
    },
    {
      id: '4',
      username: 'zhaoliu',
      nickname: '赵六',
      avatar: '/images/avatars/avatar4.jpg',
      signature: '简单生活，快乐工作',
      region: '深圳',
      isStarred: false,
      initial: 'Z'
    }
  ])

  const searchQuery = ref('')

  const starredContacts = computed(() => 
    contacts.value.filter(contact => contact.isStarred)
  )

  const filteredContacts = computed(() => {
    if (!searchQuery.value) return contacts.value
    
    const query = searchQuery.value.toLowerCase()
    return contacts.value.filter(contact => 
      contact.nickname.toLowerCase().includes(query) ||
      contact.username.toLowerCase().includes(query)
    )
  })

  const groupedContacts = computed(() => {
    const groups: Record<string, Contact[]> = {}
    filteredContacts.value.forEach(contact => {
      const initial = contact.initial || '#'
      if (!groups[initial]) {
        groups[initial] = []
      }
      groups[initial].push(contact)
    })
    return groups
  })

  const setSearchQuery = (query: string) => {
    searchQuery.value = query
  }

  const toggleStar = (contactId: string) => {
    const contact = contacts.value.find(c => c.id === contactId)
    if (contact) {
      contact.isStarred = !contact.isStarred
    }
  }

  return {
    contacts,
    starredContacts,
    searchQuery,
    filteredContacts,
    groupedContacts,
    setSearchQuery,
    toggleStar
  }
})
